package ext.opensource.netty.server.example.listen;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import ext.opensource.netty.server.example.simple.BizDispatchCollect;
import ext.opensource.netty.server.example.simple.SocketCmd;

@Component
public class ContextRefreshedListener implements ApplicationListener<ContextRefreshedEvent> {

	@Override
	public void onApplicationEvent(final ContextRefreshedEvent event) {
		System.err.println("refresh");

		final Map<String, Object> map = new HashMap<>(16);
		final Map<String, Object> bizMap = event.getApplicationContext().getBeansWithAnnotation(SocketCmd.class);
		for (final Map.Entry<String, Object> entry : bizMap.entrySet()) {
			final Object object = entry.getValue();
			final Class<? extends Object> c = object.getClass();
			final Annotation[] annotations = c.getDeclaredAnnotations();

			for (final Annotation annotation : annotations) {
				if (annotation.annotationType().equals(SocketCmd.class)) {
					final SocketCmd cmdOrder = (SocketCmd) annotation;
					if (!map.containsKey(cmdOrder.value())) {
						map.put(cmdOrder.value(), object);
					} else {
						System.err.println(String.format("Mult cmdOrder:%s className: %s", cmdOrder.value(), c));
					}
				}
			}
		}

		BizDispatchCollect.setCourses(map);
	}
}
